package com.micai.boss.user.provider.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.container.page.PageHandler;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.micai.boss.user.dto.UserDto;
import com.micai.boss.user.entity.UserEntity;
import com.micai.boss.user.mapper.UserMapper;
import com.micai.boss.user.provider.UserProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/2/24 9:36
 */
// 该注解仅仅是描述接口使用,并不会造成多次实例化
@Service(version = "1.0.0", protocol = {"dubbo", "feign"}, timeout = 10000)
public class UserProviderImpl implements UserProvider {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDto getById(Long id) {
        UserEntity userEntity = userMapper.selectById(id);
        if (userEntity == null) {
            return null;
        }
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userEntity, userDto);
        return userDto;
    }

    @Override
    public List<UserDto> getList() {
        List<UserEntity> userEntities = userMapper.selectList(new EntityWrapper<>());
        if (userEntities == null) {
            return null;
        }
        List<UserDto> userDtos = new ArrayList<>();
        for (UserEntity userEntity : userEntities) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(userEntity, userDto);
            userDtos.add(userDto);
        }
        return userDtos;
    }

    @Override
    public void save(UserDto userDto) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDto, userEntity);
        userMapper.insert(userEntity);
    }

    @Override
    public void update(UserDto userDto) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDto, userEntity);
        userMapper.updateById(userEntity);
    }

    @Override
    public void remove(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public Map<String, Object> getTaleData(int pageNum, int pageSize, String userName) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            Wrapper<UserEntity> wrapper = new EntityWrapper<>();
            wrapper.like("user_name", userName);
            List<UserEntity> userEntities = userMapper.selectList(wrapper);
            Integer count = userMapper.selectCount(wrapper);
            Map<String, Object> tableData = new HashMap<>();
            tableData.put("list", userEntities);
            tableData.put("count", count);
            return tableData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
